package org.zuel.huhuForum.controller;


import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.Comment;
import org.zuel.huhuForum.model.DiscussPost;
import org.zuel.huhuForum.model.Report;
import org.zuel.huhuForum.model.User;
import org.zuel.huhuForum.param.Page;
import org.zuel.huhuForum.service.ICommentService;
import org.zuel.huhuForum.service.IDiscussPostService;
import org.zuel.huhuForum.service.ILikeService;
import org.zuel.huhuForum.service.IUserService;
import org.zuel.huhuForum.service.Impl.*;
import org.zuel.huhuForum.util.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.zuel.huhuForum.util.DesensitizeUtil.desensitize;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关")
public class UserController implements CommunityConstant{
    @Autowired
    private IUserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ILikeService likeService;

    @Autowired
    private FollowService followService;

    @Autowired
    private IDiscussPostService discussPostService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private ReportServer reportServer;

    /**
     * 修改用户密码
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @return
     */
    @CrossOrigin
    @PostMapping("/password")
    @ApiOperation(value = "修改用户密码")
    public Map<String, Object> updatePassword(@RequestParam(name="oldPassword", required = true)String oldPassword
                            , @RequestParam(name="newPassword", required = true)String newPassword) throws InvalidKeySpecException, NoSuchAlgorithmException {
        Map<String, Object> model=new HashMap<>();
        // 验证原密码是否正确
        User user = hostHolder.getUser();
        oldPassword= PasswdUtil.privateDecrypt(oldPassword);
        String md5OldPassword = CommunityUtil.md5(oldPassword );
        if (!user.getPassword().equals(md5OldPassword)) {
            model.put("data", "原密码错误");
            model.put("code", "23");
            model.put("msg", "oldPasswordError");
            return model;
        }

        //判断新密码是否合法
        newPassword=PasswdUtil.privateDecrypt(newPassword);
        String md5NewPassword = CommunityUtil.md5(newPassword);
        if (user.getPassword().equals(md5NewPassword)) {
            model.put("data", "新密码和原密码相同");
            model.put("code", "23");
            model.put("msg", "newPasswordError");
            return model;
        }
        // 修改用户密码
        userService.updatePassword(user.getId(), newPassword);
        model.put("data", "changed");
        model.put("code", "200");
        model.put("msg", "ok");
        return model;
    }

    /**
     * 进入我的帖子（查询某个用户的帖子列表）
     * @param userId
     * @param current
     * @return
     */
    @CrossOrigin
    @PostMapping("/discuss")
    @ApiOperation(value = "进入我的帖子（查询某个用户自己发出的帖子列表）")
    @ResponseBody
    public Map<String, Object> getMyDiscussPosts(@RequestParam(name="userId", required = true) int userId,
                                 @RequestParam(name = "current",required = false) Integer current) {
        Map<String, Object> model=new HashMap<>();
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");

        }
        //避免其他用户无法访问被拉黑用户
        User owner=hostHolder.getUser();
        if(!owner.getId().equals(user.getId()) && user.getStatus().equals(TYPE_TWE)){
            model.put("data", "该用户已被拉黑！");
            model.put("code", "23");
            model.put("msg", "error");
            return model;
        }

        model.put("user", desensitize(user));

        // 该用户的帖子总数
        int rows = discussPostService.findDiscussPostRows(userId);
        model.put("rows", rows);

        Page page=new Page();
        if(current!=null){
            page.setCurrent(current);
        }
        page.setLimit(5);
        page.setPath(" "+userId);
        page.setRows(rows);

        // 分页查询(按照最新查询)
        List<DiscussPost> list = discussPostService.findDiscussPosts(userId, page.getOffset(), page.getLimit(), 0);
        // 封装帖子和该帖子对应的用户信息
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);
                long likeCount = likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPosts.add(map);
            }
        }
        model.put("discussPosts", discussPosts);
        model.put("tab", "mypost"); // 该字段用于指示标签栏高亮
        model.put("page",page);
        return model;
    }

    /**
     * 进入个人主页
     * @param userId 可以进入任意用户的个人主页
     * @return
     */
    @CrossOrigin
    @PostMapping("/profile")
    @ApiOperation(value = "进入个人主页,查看关注、粉丝、获赞情况")
    public Map<String, Object> getProfilePage(@RequestParam(name="userId", required = true)int userId) {
        Map<String, Object> model=new HashMap<>();
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        //避免其他用户无法访问被拉黑用户
        User owner=hostHolder.getUser();
        if(!owner.getId().equals(user.getId()) && user.getStatus().equals(TYPE_TWE)){
            model.put("data", "该用户已被拉黑！");
            model.put("code", "23");
            model.put("msg", "error");
            return model;
        }

        // 用户
        model.put("user", desensitize(user));
        // 获赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.put("userLikeCount", userLikeCount);
        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, CommunityConstant.ENTITY_TYPE_USER);
        model.put("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(CommunityConstant.ENTITY_TYPE_USER, userId);
        model.put("followerCount", followerCount);
        // 当前登录用户是否已关注该用户
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), CommunityConstant.ENTITY_TYPE_USER, userId);
        }
        model.put("hasFollowed", hasFollowed);
        model.put("tab", "profile"); // 该字段用于指示标签栏高亮

        return model;
    }

    /**
     * 进入我的评论/回复（查询某个用户的评论/回复列表）
     * @param userId
     * @param current
     * @return
     */
    @ApiOperation(value = "进入我的评论/回复（查询某个用户的评论/回复列表）")
    @CrossOrigin
    @PostMapping("/comment")
    public Map<String, Object> getMyComments(@RequestParam(name="userId", required = true)int userId,
                             @RequestParam(name = "current",required = false) Integer current) {
        Map<String, Object>model=new HashMap<>();
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        //避免其他用户无法访问被拉黑用户
        User owner=hostHolder.getUser();
        if(!owner.getId().equals(user.getId()) && user.getStatus().equals(TYPE_TWE)){
            model.put("data", "该用户已被拉黑！");
            model.put("code", "23");
            model.put("msg", "error");
            return model;
        }

        model.put("user", desensitize(user));

        // 该用户的评论/回复总数
        int commentCounts = commentService.findCommentCountByUserId(userId);
        model.put("commentCounts", commentCounts);
        Page page=new Page();
        if(current!=null){
            page.setCurrent(current);
        }
        page.setLimit(5);
        page.setPath("/user/comment/" + userId);
        page.setRows(commentCounts);

        // 分页查询
        List<Comment> list = commentService.findCommentByUserId(userId, page.getOffset(), page.getLimit());
        // 封装评论和该评论对应的帖子信息
        List<Map<String, Object>> comments = new ArrayList<>();
        if (list != null) {
            for (Comment comment : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", comment);
                // 显示评论/回复对应的文章信息
                if (comment.getEntityType() == CommunityConstant.ENTITY_TYPE_POST) {
                    // 如果是对帖子的评论，则直接查询 target_id 即可
                    DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                    map.put("post", post);
                }
                else if (comment.getEntityType() == CommunityConstant.ENTITY_TYPE_COMMENT) {
                    // 如过是对评论的回复，则先根据该回复的 target_id 查询评论的 id, 再根据该评论的 target_id 查询帖子的 id
                    Comment targetComment = commentService.findCommentById(comment.getEntityId());
                    DiscussPost post = discussPostService.findDiscussPostById(targetComment.getEntityId());
                    map.put("post", post);
                }

                comments.add(map);
            }
        }
        model.put("comments", comments);
        model.put("tab", "myreply"); // 该字段用于指示标签栏高亮
        model.put("page",page);
        return model;
    }

        /**
     * 激活用户状态
     */
    @CrossOrigin
    @PostMapping("/updateState")
    @ApiOperation(value = "修改用户状态 0-取消激活 1-激活用户 2-拉黑用户")
    public Map<String,String> updateState(@RequestParam(name = "userID",required = true) Integer userid,
                              @RequestParam(name = "state",required = true) Integer state) {
        Map<String,String>model =new HashMap<>();
        if(state!=1 && state!=2){
            model.put("data", "激活状态只能为1或2");
            model.put("code", "23");
            model.put("msg", "error");
            return model;
        }
        boolean flag=userService.updateState(userid, state);
        if(!flag){
            model.put("data", "状态修改失败");
            model.put("code", "23");
            model.put("msg", "error");
            return model;
        }
        model.put("data", "状态修改成功");
        model.put("code", "200");
        model.put("msg", "ok");
        return model;
    }
    /**
     * 激活用户状态
     */
    @CrossOrigin
    @PostMapping("/selectState")
    @ApiOperation(value = "查询未激活用户")
    public Map<String,Object> selectState() {
        Map<String,Object>model =new HashMap<>();
        List<User> list=userService.selectState();
        model.put("list", list);
        model.put("data", "查询成功");
        model.put("code", "200");
        model.put("msg", "ok");
        return model;
    }


    /**
     * 举报用户
     */
    @CrossOrigin
    @PostMapping("/report")
    @ApiOperation(value = "举报用户")
    public Map<String,Object> report(@RequestParam(name = "reportedUserid",required = true) Integer reportid,
                                     @RequestParam(name = "reason",required = true) String reason,
                                     @RequestParam(name = "url",required = true) String url) {
        Map<String,Object>model =new HashMap<>();
        User user=hostHolder.getUser();
        boolean flag=reportServer.addReport(user.getId(), reportid, reason, url);
        model.put("data", "举报成功");
        model.put("code", "200");
        model.put("msg", flag);
        return model;
    }

    /**
     * 举报情况列表
     */
    @CrossOrigin
    @PostMapping("/reportlist")
    @ApiOperation(value = "举报情况汇总")
    public Map<String,Object> reportedList() {
        Map<String,Object>model =new HashMap<>();
        List<Report> list=reportServer.list();
        model.put("data", list);
        model.put("code", "200");
        model.put("msg", "ok");
        return model;
    }

    /**
     * 处理举报情况
     */
    @CrossOrigin
    @PostMapping("/doReport")
    @ApiOperation(value = "处理举报情况")
    public Map<String,Object> doReported(@RequestParam(name = "reportid",required = true) Integer reportid) {
        Map<String,Object>model =new HashMap<>();
        Integer state=reportServer.update(reportid);
        model.put("data", state);
        model.put("code", "200");
        model.put("msg", "ok");
        return model;
    }

}
